package com.sakura.flowers.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.sakura.flowers.entity.Card;
import com.sakura.flowers.entity.CardFlower;
import com.sakura.flowers.entity.Flower;
import com.sakura.flowers.service.CardFlowerService;
import com.sakura.flowers.service.CardService;
import com.sakura.flowers.util.R;
import com.sakura.flowers.vo.CardVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * (Card)表控制层
 *
 * @author Sakura
 * @since 2023-11-26 17:07:05
 */
@Api(value = "/api/card", tags = {"(Card)表控制层"})
@RestController
@RequestMapping("/api/card")
@CrossOrigin
public class CardController {
/**
 * 服务对象
 */
    @Resource
    private CardService cardService;
    @Resource
    private CardFlowerService cardFlowerService;
    @Resource
    private com.sakura.flowers.service.FlowerService FlowerService;

    /**
     * 分页查询
     *
     * @param pageNo    当前页
     * @param pageSize  数据大小
      * @param searchKey 查询参数
     * @return 查询结果
     */
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", dataType = "int", name = "pageNo", value = "当前页", required = true),
            @ApiImplicitParam(paramType = "path", dataType = "int", name = "pageSize", value = "数据大小", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "string", name = "searchKey", value = "查询参数")
    })
    @ApiOperation(value = "分页查询", notes = "分页查询", httpMethod = "GET")
    @GetMapping("/{pageNo}/{pageSize}")
    public R queryByPage(@PathVariable Integer pageNo,
                                       @PathVariable Integer pageSize,
                                       @RequestParam(required = false) String searchKey) {
        return R.success(this.cardService.queryByPage(pageNo,pageSize,searchKey));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", dataType = "long", name = "id", value = "主键", required = true)
    })
    @ApiOperation(value = "通过主键查询单条数据", notes = "通过主键查询单条数据", httpMethod = "GET")
    @GetMapping("{id}")
    public R<Card> queryById(@PathVariable("id") Long id) {
        return R.success(this.cardService.getById(id));
    }

    /**
     * 新增数据
     *
     * @param
     * @return 新增结果
     */
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body", dataType = "Card", name = "card", value = "实体", required = true)
    })
    @ApiOperation(value = "新增数据", notes = "新增数据", httpMethod = "POST")
    @PostMapping("/{userId}")
    public R add(@RequestBody CardFlower cardFlower, @PathVariable("userId") long userId) {
        System.out.println(userId);
        LambdaQueryWrapper<Card> cardLambdaQueryWrapper=new LambdaQueryWrapper<>();
        cardLambdaQueryWrapper.eq(Card::getUserId,userId);
        Card card= cardService.getOne(cardLambdaQueryWrapper);
        Card newCard=new Card();
        if (card==null){
            newCard.setUserId(userId);
            newCard.setCreateTime(new Date());
            this.cardService.save(newCard);
        }
        long cardId=card==null?newCard.getId():card.getId();

        LambdaQueryWrapper<CardFlower> cardFlowerLambdaQueryWrapper=new LambdaQueryWrapper<>();
        cardFlowerLambdaQueryWrapper.eq(CardFlower::getFlowerId,cardFlower.getFlowerId());
        cardFlowerLambdaQueryWrapper.eq(CardFlower::getCardId,cardId);
        CardFlower cardFlower1 = cardFlowerService.getOne(cardFlowerLambdaQueryWrapper);
        boolean result1=false;
        boolean result2=false;
        if (cardFlower1!=null) {
            cardFlower1.setSum(cardFlower1.getSum()+cardFlower.getSum());
             result1 = cardFlowerService.updateById(cardFlower1);
        }else{
            CardFlower cardFlower2=new CardFlower();
            cardFlower2.setCardId(cardId);
            cardFlower2.setFlowerId(cardFlower.getFlowerId());
            cardFlower2.setSum(cardFlower.getSum());
            cardFlower2.setSelected(0);
             result2 = cardFlowerService.save(cardFlower2);
        }
        if(result1||result2){
            return R.success("添加成功");
        }
        return R.error("添加失败");
    }

    /**
     * 编辑数据
     *
     * @param
     * @return 编辑结果
     */
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body", dataType = "Card", name = "card", value = "实体", required = true)
    })
    @ApiOperation(value = "编辑数据", notes = "编辑数据", httpMethod = "PUT")
    @PutMapping
    public R edit(@RequestBody CardFlower cardFlower) {
//        int result = cardFlowerService.updateSum(cardFlower.getId(),cardFlower.getSum());
        boolean result = cardFlowerService.updateById(cardFlower);
        if(result==false){
           return R.error("修改失败");
        }
        return R.success("修改成功");
    }
    @ApiOperation(value = "编辑数据", notes = "编辑数据", httpMethod = "PUT")
    @PutMapping("/all/{selected}")
    public R exitAll(@PathVariable("selected") Integer selected) {
        System.out.println(selected);
        boolean result=this.cardFlowerService.updateAll(selected);
        if(result==false){
           return R.error("修改失败");
        }
        return R.success("修改成功");
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", dataType = "long", name = "id", value = "主键", required = true)
    })
    @ApiOperation(value = "删除数据", notes = "删除数据", httpMethod = "DELETE")
    @DeleteMapping("/{id}")
    public R deleteById(@PathVariable Long id) {
        boolean result = cardFlowerService.removeById(id);
        if(!result){
           return R.error("删除失败");
        }
        return R.success("删除成功");
    }

    @GetMapping("/select/list")
    public R getSelectList(@RequestParam long id) {
        LambdaQueryWrapper<Card> lambdaQueryWrapper=new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(Card::getUserId,id);
        Card card = cardService.getOne(lambdaQueryWrapper);
        List<CardFlower> cardFlowers=new ArrayList<>();
        if (card!=null){
            LambdaQueryWrapper<CardFlower> cardFlowerQueryWrapper=new LambdaQueryWrapper();
            cardFlowerQueryWrapper.eq(CardFlower::getCardId,card.getId());
            cardFlowers = cardFlowerService.list(cardFlowerQueryWrapper);
        }
        List<CardVO> cardVOS=new ArrayList<>();
        long i=0;
        for (CardFlower cardFlower : cardFlowers) {
            Flower Flower = FlowerService.getById(cardFlower.getFlowerId());
            CardVO cardVO=new CardVO();
            cardVO.setCount(cardFlower.getSum());
            cardVO.setPicture(Flower.getImage());
            cardVO.setAttrsText(Flower.getContent());
            cardVO.setPrice(Flower.getPrice());
            cardVO.setName(Flower.getName());
            cardVO.setSelected(cardFlower.getSelected()==0?false:true);
            cardVO.setId(cardFlower.getId());
            cardVO.setMid(Flower.getId());
            cardVOS.add(cardVO);
        }
        return R.success(cardVOS);
    }

    @GetMapping("/select/checkInfo")
    public R getCheckInfo(@RequestParam long id) {
        LambdaQueryWrapper<Card> lambdaQueryWrapper=new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(Card::getUserId,id);
        Card card = cardService.getOne(lambdaQueryWrapper);
        List<CardFlower> cardFlowers=new ArrayList<>();
        if (card!=null){
            LambdaQueryWrapper<CardFlower> cardFlowerQueryWrapper=new LambdaQueryWrapper();
            cardFlowerQueryWrapper.eq(CardFlower::getCardId,card.getId());
            cardFlowerQueryWrapper.eq(CardFlower::getSelected,1);
            cardFlowers = cardFlowerService.list(cardFlowerQueryWrapper);
        }
        List<CardVO> cardVOS=new ArrayList<>();
        long i=0;
        for (CardFlower cardFlower : cardFlowers) {
            Flower Flower = FlowerService.getById(cardFlower.getFlowerId());
            CardVO cardVO=new CardVO();
            cardVO.setCount(cardFlower.getSum());
            cardVO.setPicture(Flower.getImage());
            cardVO.setAttrsText(Flower.getContent());
            cardVO.setPrice(Flower.getPrice());
            cardVO.setName(Flower.getName());
            cardVO.setSelected(cardFlower.getSelected()==0?false:true);
            cardVO.setId(cardFlower.getId());
            cardVO.setMid(Flower.getId());
                cardVOS.add(cardVO);
        }
        return R.success(cardVOS);
    }

}
